package englishBusiness;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import easyDAO.SqlDispatch;
import impl.TestServerBusinessImpl;
import models.MyConfig;
import models.ReturnJson;
import models.SqlReturnModel;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * Created by yangxianming on 2020/1/1.
 * abc
 */
public class GetWords implements TestServerBusinessImpl {
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        ReturnJson returnJson = new ReturnJson();
        //读取请求json
        InputStreamReader inputStreamReader;
        BufferedReader bufferedReader;
        String requestInfo = "";
        JSONObject jsonRequest;

        try {
            inputStreamReader = new InputStreamReader(request.getInputStream(), "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null)
                requestInfo = requestInfo + line;
            System.out.println(requestInfo);
            jsonRequest = JSON.parseObject(requestInfo);
        }catch (Exception e){
            //请求流如果出现异常的时候
            returnJson.setApiStatus(0);
            returnJson.setErrorMsg(e.getMessage());
            return returnJson.toString();
        }

        //从单词表拿数据
        if (Objects.equals("getWords", jsonRequest.getString("action"))){
            //SELECT word,chinese,forget FROM words WHERE `week`="1" AND LIMIT 10,5
            String from = jsonRequest.getJSONObject("body").getString("from");
            String to = jsonRequest.getJSONObject("body").getString("to");
            String forget = jsonRequest.getJSONObject("body").getString("forget");

            String where = " WHERE `week`=\"" + getWeekIndex() + "\"";
//            String where = " WHERE `week`=\"2\"";
            String orderBy = "";
            String limit = " LIMIT " + from + ","+to;
            if (Objects.equals(forget, "2")){
                where = where + " AND `forget`>0 ";
                orderBy = " ORDER BY forget DESC  ";
                limit = ""; //获取遗忘词，就不需要分段查询了
            }
            String sql = "SELECT word,chinese,forget FROM words " + where + orderBy + limit;

            SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
            SqlReturnModel sqlReturnModel = sqlDispatch.selectWord(sql);
            if (sqlReturnModel.getIsSuccess()){
                if (Objects.equals(forget, "2")){
                    returnJson.setResult(getHundredMistake(sqlReturnModel.getSelectReturnDataAsJsonArray()));
                }else {
                    returnJson.setResult(sqlReturnModel.getSelectReturnDataAsJsonArray());
                }
            }else {
                returnJson.setApiStatus(0);
                returnJson.setErrorMsg(sqlReturnModel.getFailingReason());
            }
            returnJson.setApiStatus((sqlReturnModel.getIsSuccess()) ? 1 : 0);
        }
        //拿到词组
        if (Objects.equals("getPhrase", jsonRequest.getString("action"))){
            //SELECT word,chinese,forget FROM words WHERE `week`="1" LIMIT 10,5
            String from = jsonRequest.getJSONObject("body").getString("from");
            String to = jsonRequest.getJSONObject("body").getString("to");
            String where = " WHERE `week`=\"" + getWeekIndex() + "\"";
            String limit = " LIMIT " + from + ","+to;
            String sql = "SELECT phrase,chinese,forget FROM phrase " + where + limit;

            SqlDispatch sqlDispatch = new SqlDispatch(myConfig);
            SqlReturnModel sqlReturnModel = sqlDispatch.selectWord(sql);
            if (sqlReturnModel.getIsSuccess()){
                returnJson.setResult(sqlReturnModel.getSelectReturnDataAsJsonArray());
            }else {
                returnJson.setApiStatus(0);
                returnJson.setErrorMsg(sqlReturnModel.getFailingReason());
            }
            returnJson.setApiStatus((sqlReturnModel.getIsSuccess()) ? 1 : 0);
        }
        return returnJson.toString();
    }

    //拿100个forget词，大于100个顺序取30个余下随机取70个
    private JSONArray getHundredMistake(JSONArray jsonArray){
        JSONArray hundredMistake = new JSONArray();
        if (jsonArray.size() <= 100){
            return jsonArray;
        }else {
            for (int i = 0; i < 30; i++){
                hundredMistake.add(jsonArray.get(i));
                jsonArray.remove(i);
            }
            for (int i = 0; i < 70; i++){
                Random random = new Random();
                int index = random.nextInt(jsonArray.size());
                hundredMistake.add(jsonArray.get(index));
                jsonArray.remove(index);
            }
            return hundredMistake;
        }
    }

    private String getWeekIndex(){
        String[] weeks = {"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
        String week = sdf.format(new Date());
        for (int i = 0; i < weeks.length; i++){
            if (Objects.equals(week, weeks[i])){
                return String.valueOf(i+1);
            }
        }
        return "";
    }
}
